<?php
/**
 * 小程序添加用户信息
 */

namespace app\mini\controller;
use think\paginator\driver\Bootstrap;
header('Access-Control-Allow-Origin:*');
class Message extends Pre
{
    //添加，修改
    public function inserts(){
        $account =new \app\common\model\Message();
        return $account -> inserts($this -> loginInfo);
    }


    //用户列表筛选
    public function lists(){
        $data = $this -> data;
        $loginInfo = $this -> loginInfo;
        //轮牌用户
        if (in_array($loginInfo['role'],['22','23','26','27'])){
            $turns =new \app\common\model\Turns();
            $turns -> inserts($loginInfo);
        }

        //获取我开的所有账号，渠道经理
        if ($loginInfo['role'] =='14'){
            $findID = $loginInfo -> higher -> a_id;
        }
        else{
            $findID = $loginInfo['id'];
        }
        $allAcount = Account::allAcount($findID);


        //构建查询条件,用户姓名/手机号/备注/经纪人姓名
        if ($data['key'])
            $findMap[] = ['name|telephone|notes','like',"%$data[key]%"];

        if ($data['visit'])
            $findMap[] = ['visit','neq',''];

        if ($data['building'])
            $findMap[] = ['building','eq',$data['building']];
        if ($data['status'])
            $findMap[] = ['status','eq',$data['status']];
        if ($data['endDate']){
            if ($data['startDate']){
                $findMap[] = ['time','between',[strtotime($data['startDate']),strtotime($data['endDate'])]];
            }
            else{
                $findMap[] = ['time','elt',strtotime($data['endDate'])];
            }
        }
        else{
            if ($data['startDate'])
                $findMap[] = ['time','egt',strtotime($data['startDate'])];
        }

        if ($data['today']){
            $findMap[] = ['schedule','elt',strtotime(date('Y-m-d',strtotime('+1 day')))];
            $findMap[] = ['status','in',['跟进中','星标']];
        }

        //按经纪人搜索时，搜索经纪人以及他开出账号的所有的
        if ($data['agent']){
            if ($data['agent_single']){
                $findMap[] = ['account_id','eq',$data['agent']];
            }
            else{
                $allAcount = Account::allAcount($data['agent']);
                $findMap[] = ['account_id','in',$allAcount];
            }
        }
        else{
            $findMap[] = ['account_id','in',$allAcount];
        }

        $infoPre = \app\common\model\Message::
            with('turnsInfo,buildingInfo,accountInfo.higher.AInfo,followInfoEnd')
            ->where($findMap)
            ->order('time desc')
            -> select()
            ->toArray();



        //自定义排序
        if ($data['order']){
            switch ($data['order']){
                //录入时间远到近
                case 'at11':
                    usort($infoPre,function ($a,$b){
                        if ($a['time'] == $b['time'])
                            return 0;
                        return ($a['time'] > $b['time']) ?-1 :1;
                    });
                    break;
                    //录入时间近到远
                case 'at22':
                    usort($infoPre,function ($a,$b){
                        if ($a['time'] == $b['time'])
                            return 0;
                        return ($a['time'] < $b['time']) ?-1 :1;
                    });
                    break;
                    //约访时间远到近
                case 'ft11':
                    usort($infoPre,function ($a,$b){
                        if ($a['schedule'] == $b['schedule'])
                            return 0;
                        return ($a['schedule'] > $b['schedule']) ?-1 :1;
                    });
                    break;
                    //约访时间近到远
                case 'ft22':
                    usort($infoPre,function ($a,$b){
                        if ($a['schedule'] == $b['schedule'])
                            return 0;
                        return ($a['schedule'] < $b['schedule']) ?-1 :1;
                    });
                    break;
            }
            $infoArr = $infoPre;
        }
        else{
            //渠道默认排序,新近-》3天到期-》录入最新-》星标
            if ($this -> channel){
                $newUser = [];
                $starUser = [];
                $timeUser = [];
                $commonUser = [];

                foreach ($infoPre as $value){
                    if ($value['turns_mark'] =='1'){
                        $newUser[] = $value;
                    }
                    elseif($value['status'] =='星标'){
                        $starUser[] = $value;
                    }
                    elseif((time() - $value['turns_info']['date'])>3600*24*11 && $value['status'] =='跟进中'){
                        $value['time_mark'] = 1;
                        $timeUser[] = $value;
                    }
                    else{
                        $commonUser[] = $value;
                    }
                }

                //新近客户新到旧
                usort($newUser,function ($a,$b){
                    if ($a['turns_info']['date'] == $b['turns_info']['date'])
                        return 0;
                    return ($a['turns_info']['date'] > $b['turns_info']['date']) ?-1 :1;
                });
                //倒计时客户旧到新
                usort($timeUser,function ($a,$b){
                    if ($a['turns_info']['date'] == $b['turns_info']['date'])
                        return 0;
                    return ($a['turns_info']['date'] < $b['turns_info']['date']) ?-1 :1;
                });
                //星标客户旧到新
                usort($starUser,function ($a,$b){
                    if ($a['turns_info']['date'] == $b['turns_info']['date'])
                        return 0;
                    return ($a['turns_info']['date'] > $b['turns_info']['date']) ?-1 :1;
                });
                $infoArr = array_merge($newUser,$timeUser,$commonUser,$starUser);
                foreach ($infoArr as $k=> $value){
                    $infoArr[$k]['turns_date'] = secToTime(14*24*3600+$value['turns_info']['date']-time());
                    $infoArr[$k]['star_date'] = date('Y-m-d H:i:s',$value['star_date']);
                    $infoArr[$k]['date'] = date('Y-m-d H:i:s',$value['date']);
                }
            }
            //代理客户默认排序
            else{
                //新近客户新到旧
                usort($infoPre,function ($a,$b){
                    if ($a['time'] == $b['time'])
                        return 0;
                    return ($a['time'] > $b['time']) ?-1 :1;
                });
                $infoArr = $infoPre;
            }
        }



        foreach ($infoArr as $k=> $value){
            if ($value['turns_info'])
                $infoArr[$k]['turns_info']['date'] = secToTime(14*24*3600+$value['turns_info']['date']-time());
            //罗宅，房金,部门经理,自己能看全号
            if($value['account_id'] != $loginInfo['id'])
                if (!in_array($loginInfo['role'],['21','30','8']) )
                $infoArr[$k]['telephone'] = substr_replace($value['telephone'],'****',3,4);
        }

        //分页
        if (!$data['count'])
            $data['count'] = count($infoArr);
        $curpage = $data['start']/$data['count'] + 1;//当前第x页，有效值为：1,2,3,4,5...
        $listRow = $data['count'];//每页2行记录
        $showdata = array_chunk($infoArr, $data['count'], true)[$curpage-1];
        $info = Bootstrap::make($showdata, $listRow, $curpage, count($infoArr), false, [
            'var_page' => 'page',
            'path'     => url('/service/index/record'),//这里根据需要修改url
            'query'    => [],
            'fragment' => '',
        ]);

        $num = \app\common\model\Message::where($findMap)->count();


        //今日约访数量
        $findSheduleMap[] = ['schedule','elt',strtotime(date('Y-m-d',strtotime('+1 day')))];
        $findSheduleMap[] = ['status','in',['跟进中','星标']];
        $findSheduleMap[] = ['account_id','in',$allAcount];
        $scheduleNum = \app\common\model\Message::where($findSheduleMap)->count();

        return [
            'content' => $info->toArray()['data'],
            'scheduleNum' => $scheduleNum,
            'num' => $num,
            'add' => strpos($loginInfo['fun'],'2') === false?false:true
        ];
    }

    //查看用户详情
    public function detail(){
        $id = input('id');
        //轮牌用户
        $loginInfo = $this -> loginInfo;
        if (in_array($loginInfo['role'],['22','23','26','27'])){
            $turns =new \app\common\model\Turns();
            $turns -> inserts($loginInfo);
        }
        $info = \app\common\model\Message::with(['transferInfo'=>['accountInfo','buildingInfo'],'accountInfo.roleInfo','visitInfo','followInfo.accountInfo.roleInfo','dealInfo','buildingInfo','turnsInfo'])->where('id',$id)->find();
        if ($info['account_id'] != $loginInfo['id'])
            if ($info['transfer_info']['to_account_id'] != $loginInfo['id'])
                if (!in_array($loginInfo['role'],['8']) )
                    $info['telephone'] = substr_replace($info['telephone'],'****',3,4);
        $info['time'] = date('Y-m-d H:i:s',$info['time']);
        $info['schedule'] = date('Y-m-d H:i:s',$info['schedule']);
        foreach ($info['follow_info'] as $k => $value){
            $info['follow_info'][$k]['date'] = date('Y-m-d H:i:s',$value['date']);
        }

//        if ($info['turns_mark'] =='1')
//            if ($loginInfo['id'] == $info['account_id'])
//                \app\common\model\Message::where('id',$id)->update(['turns_mark' =>'0']);

        //获取该部门的其他经纪人
        $otherStaff = $this -> otherStaff($loginInfo);

        return [
            'content' => $info,
            'staff' => $otherStaff
        ];
    }

    //获取转介对象
    public function otherStaff($loginInfo){
        //全民获取我的上级所在部门
        if ($loginInfo['role'] == '33'){
            $higher_id_1 = $loginInfo -> higher -> a_id;
            $higher_1_info = \app\common\model\Account::get($higher_id_1);
            $higher_id = $higher_1_info -> higher -> a_id;
        }
        //部门经理
        elseif ($loginInfo['role'] ='8'){
            $higher_id = $loginInfo['id'];
        }
        //获取我部门所有的人
        else{
            $higher_id = $loginInfo -> higher -> a_id;
        }

        if ($higher_id){
            $findMap[] = ['b_id','neq',$loginInfo['id']];
            $findMap[] = ['a_id','eq',$higher_id];
            $allBID = \app\common\model\Record::where($findMap)->column('b_id');
            if ($allBID){
                $findInfo[] = ['id','in',$allBID];
                $findInfo[] = ['role','neq','33'];
                $info = \app\common\model\Account::where($findInfo)->field('name,id')->select();
            }

        }

        return $info;
    }

    /**
     * 上传到访凭证文件
     * @param string file 提交文件名
     * @param int message_id 用户ID
     * @return array 返回信息
     */
    public function insertVisit(){
        $data = input('param.');
        if (!$data['message_id'])
            return [
                'message' => 'message_id不能为空'
            ];

        $URL = "./static/upload/visit/";
        //上传文件
        $upload = new \app\common\logic\Upload();
        $pathName = $upload -> img('file',$URL);
        $addData = [];
        foreach ($pathName as $value){
            if ($value)
                $addData[] = [
                    'message_id' => $data['message_id'],
                    'content' => ltrim($value,'.'),
                    'date' => time()
                ];
        }
        $visit = new \app\common\model\Visit();
        $visit -> insertAll($addData);
        return json([
            'code' => '1',
            'message' => '上传成功',
            'pathName' => $pathName,
        ]);
    }

    /**
     * 删除到访凭证文件
     * @param int message_id 用户ID
     * @return array 返回信息
     */
    public function delVisit(){
        $id = input('param.id');
        if (!$id)
            return [
                'message' => 'id不能为空'
            ];

        \app\common\model\Visit::destroy($id);

        return json([
            'code' => '1',
            'message' => '删除成功',
        ]);
    }

    /**
     * 历史轨迹（录入/转介/撤回/轮牌/结佣/账号删除被分配）
     */
}